package com.example.juccode.juc02completableFuture.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhongkui 1365693530@qq.com
 * @Date: 2025/2/9
 */
public class FutureThreadPoolDemo {

    // 3个任务，只有多个线程线程，执行需要的时间
    public static void main(String[] args) {
        long startTiem = System.currentTimeMillis();
        //使用线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        FutureTask<String> futureTask1 = new FutureTask<>(() -> {
            try {TimeUnit.MILLISECONDS.sleep(300);} catch (Exception e) {e.printStackTrace();}
            return "task1 over";
        });
        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            try {TimeUnit.MILLISECONDS.sleep(300);} catch (Exception e) {e.printStackTrace();}
            return "task2 over";
        });
        threadPool.submit(futureTask1);
        threadPool.submit(futureTask2);
        try {TimeUnit.MILLISECONDS.sleep(300);} catch (Exception e) {e.printStackTrace();}
        threadPool.shutdown();

        long entTiem = System.currentTimeMillis();
        System.out.println("耗费时间为：" + (entTiem - startTiem));

        System.out.println(Thread.currentThread().getName() + "------执行完毕");

//        耗费时间为：358
//        Main------执行完毕

    }


    // 3个任务，只有一个主线程执行需要的时间
    public static void m1(String[] args) {

        long startTiem = System.currentTimeMillis();

        try {TimeUnit.MILLISECONDS.sleep(300);}catch (Exception e){e.printStackTrace();}

        try {TimeUnit.MILLISECONDS.sleep(300);}catch (Exception e){e.printStackTrace();}

        try {TimeUnit.MILLISECONDS.sleep(300);}catch (Exception e) {e.printStackTrace();}

        long entTiem = System.currentTimeMillis();
        System.out.println("耗费时间为：" + (entTiem - startTiem));

        System.out.println(Thread.currentThread().getName() + "------执行完毕");

//        耗费时间为：916
//        Main------执行完毕
    }
}
